#include "fileeditwin.h"
#include "ui_fileeditwin.h"
#include <QFileDialog>
#include <QFile>
#include <QDebug>
#include <QMessageBox>
#include <QAction>

FileEditWin::FileEditWin(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::FileEditWin)
{
    ui->setupUi(this);
    //在工具栏中添加action
    QAction *openA = new QAction();
    QIcon icon(":/file.png");
    openA->setIcon(icon);
    ui->mainToolBar->addAction(openA);

    //直接添加Action
    QAction *newA = ui->mainToolBar->addAction("new");
    //添加分割线
    ui->mainToolBar->addSeparator();

    //把openA的triggered信号关联到on_actionopen_triggered
    connect(openA,&QAction::triggered,this,&FileEditWin::on_actionopen_triggered);

}

FileEditWin::~FileEditWin()
{
    delete ui;
}

void FileEditWin::on_actionopen_triggered()
{
    //获取文件路径
   filename =  QFileDialog::getOpenFileName(this);
   //创建文件对象
   QFile file(filename);
   if(!file.open(QIODevice::ReadOnly)){
       qDebug()<<"open fail!!";
       return;
   }

   //清空编辑框
   ui->textEdit->clear();


   //读取文件
   //判断文件是否在末尾了
   while(!file.atEnd()){
       QByteArray array = file.read(1024);
       ui->textEdit->append(array); //追加
       qDebug()<<array.size();
   }

   //关闭文件
   file.close();

}

void FileEditWin::save_file(QString filename)
{
   //创建文件对象
   QFile file(filename);
   //只写权限
   if(!file.open(QIODevice::WriteOnly)){
       qDebug()<<"open fail!!";
       return;
   }

   //获取编辑框中的内容
   QString data = ui->textEdit->toPlainText();

   //写文件
   file.write(data.toUtf8());

   //关闭文件
   file.close();
}


void FileEditWin::on_actionsaveAs_triggered()
{
    //另存为
    //获取文件路径
   filename =  QFileDialog::getSaveFileName(this);
   save_file(filename);
}



void FileEditWin::on_actionclose_triggered()
{
    //提示
    int ret = QMessageBox::warning(this,"退出提示","文件已改变，是否保存",QMessageBox::Yes,QMessageBox::No);
    if(ret == QMessageBox::Yes){
        save_file(filename);
    }

    this->close();

}


